﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using Xunit;
using System;
using System.Xml.Serialization;
using System.Linq;
using static System.Net.Mime.MediaTypeNames;


namespace OrderManagement
{
   
    public class OrderDetails
    {
        public string ProductName { get; set; }
        public int Quantity { get; set; }
        public decimal Price { get; set; }
        public decimal Total => Quantity * Price;

        public override bool Equals(object obj)
        {
            return obj is OrderDetails details &&
                   ProductName == details.ProductName;
        }

        public override int GetHashCode()
        {
            return ProductName.GetHashCode();
        }

        public override string ToString()
        {
            return $"{ProductName} x{Quantity} @{Price:C} = {Total:C}";
        }
    }

    public class Order
    {
        public string OrderId { get; set; }
        public string Customer { get; set; }
        public List<OrderDetails> Details { get; } = new List<OrderDetails>();
        public decimal TotalAmount => Details.Sum(d => d.Total);

        public override bool Equals(object obj)
        {
            return obj is Order order &&
                   OrderId == order.OrderId;
        }

        public override int GetHashCode()
        {
            return OrderId.GetHashCode();
        }

        public void AddDetail(OrderDetails detail)
        {
            if (Details.Contains(detail))
                throw new ArgumentException("商品已存在。");
            Details.Add(detail);
        }

        public override string ToString()
        {
            return $"订单号: {OrderId}, 客户: {Customer}, 总金额: {TotalAmount:C}\n明细:\n{string.Join("\n", Details)}";
        }
    }

    public class OrderService
    {
        private List<Order> orders = new List<Order>();

        public void AddOrder(Order order)
        {
            if (orders.Contains(order))
                throw new ArgumentException("订单已存在。");
            orders.Add(order);
        }

        public void DeleteOrder(string orderId)
        {
            var order = orders.FirstOrDefault(o => o.OrderId == orderId);
            if (order == null)
                throw new KeyNotFoundException("订单不存在。");
            orders.Remove(order);
        }

        public void UpdateOrder(Order order)
        {
            DeleteOrder(order.OrderId);
            orders.Add(order);
        }

        public IEnumerable<Order> Query(Func<Order, bool> condition)
        {
            return orders.Where(condition).OrderBy(o => o.TotalAmount);
        }

        public void Sort(Comparison<Order> comparison = null)
        {
            if (comparison == null)
                orders = orders.OrderBy(o => o.OrderId).ToList();
            else
                orders.Sort(comparison);
        }
        public void Export(string filePath)
        {
            using (var writer = new StreamWriter(filePath))
            {
                var serializer = new XmlSerializer(typeof(List<Order>));
                serializer.Serialize(writer, orders);
            }
        }

        public void Import(string filePath)
        {
            if (!File.Exists(filePath)) throw new FileNotFoundException();

            using (var reader = new StreamReader(filePath))
            {
                var serializer = new XmlSerializer(typeof(List<Order>));
                var importedOrders = (List<Order>)serializer.Deserialize(reader);
                orders.Clear();
                orders.AddRange(importedOrders);
            }
        }
    }
    public class OrderServiceTests
    {
        private OrderService CreateTestService()
        {
            var service = new OrderService();
            service.AddOrder(new Order { OrderId = "001", Customer = "Alice" });
            return service;
        }

        [Fact]
        public void AddOrder_DuplicateId_ThrowsException()
        {
            var service = CreateTestService();
            var order = new Order { OrderId = "001" };
            Assert.Throws<ArgumentException>(() => service.AddOrder(order));
        }

        [Fact]
        public void DeleteOrder_ExistingOrder_RemovesFromList()
        {
            var service = CreateTestService();
            service.DeleteOrder("001");
            Assert.Empty(service.Query(o => true));
        }

        [Fact]
        public void ImportExport_RoundTrip_PreservesData()
        {
            var tempFile = Path.GetTempFileName();
            var service = CreateTestService();

            service.Export(tempFile);
            var newService = new OrderService();
            newService.Import(tempFile);

            Assert.Equal(service.Query(o => true).Count(), newService.Query(o => true).Count());
            File.Delete(tempFile);
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            OrderService service = new OrderService();
            while (true)
            {
                Console.WriteLine("\n1.添加订单 2.删除订单 3.修改订单 4.查询订单 5.排序 6.退出");
                switch (Console.ReadLine())
                {
                    case "1":
                        AddOrder(service);
                        break;
                    case "2":
                        DeleteOrder(service);
                        break;
                    case "3":
                        ModifyOrder(service);
                        break;
                    case "4":
                        QueryOrders(service);
                        break;
                    case "5":
                        service.Sort();
                        break;
                    case "6":
                        return;
                }
            }
        }

        static void AddOrder(OrderService service)
        {
            try
            {
                var order = new Order();
                Console.Write("订单号:");
                order.OrderId = Console.ReadLine();
                Console.Write("客户:");
                order.Customer = Console.ReadLine();

                while (true)
                {
                    var detail = new OrderDetails();
                    Console.Write("商品名 (回车结束):");
                    string name = Console.ReadLine();
                    if (string.IsNullOrEmpty(name)) break;

                    detail.ProductName = name;
                    Console.Write("数量:");
                    detail.Quantity = int.Parse(Console.ReadLine());
                    Console.Write("单价:");
                    detail.Price = decimal.Parse(Console.ReadLine());

                    order.AddDetail(detail);
                }
                service.AddOrder(order);
            }
            catch (Exception e) { Console.WriteLine($"错误: {e.Message}"); }
        }

        static void DeleteOrder(OrderService service)
        {
            try
            {
                Console.Write("删除订单号:");
                service.DeleteOrder(Console.ReadLine());
            }
            catch (Exception e) { Console.WriteLine($"错误: {e.Message}"); }
        }

        static void ModifyOrder(OrderService service)
        {
            try
            {
                Console.Write("修改订单号:");
                var oldId = Console.ReadLine();
                var order = service.Query(o => o.OrderId == oldId).FirstOrDefault();
                if (order == null) throw new KeyNotFoundException();

                Console.Write("新客户(留空不变):");
                var newCustomer = Console.ReadLine();
                if (!string.IsNullOrEmpty(newCustomer)) order.Customer = newCustomer;

                service.UpdateOrder(order);
            }
            catch (Exception e) { Console.WriteLine($"错误: {e.Message}"); }
        }

        static void QueryOrders(OrderService service)
        {
            Console.Write("查询条件 (1:订单号 2:商品名 3:客户 4:金额下限):");
            var condition = Console.ReadLine();
            IEnumerable<Order> result = null;

            switch (condition)
            {
                case "1":
                    Console.Write("订单号:");
                    result = service.Query(o => o.OrderId == Console.ReadLine());
                    break;
                case "2":
                    Console.Write("商品名:");
                    result = service.Query(o => o.Details.Any(d => d.ProductName == Console.ReadLine()));
                    break;
                case "3":
                    Console.Write("客户:");
                    result = service.Query(o => o.Customer == Console.ReadLine());
                    break;
                case "4":
                    Console.Write("最低金额:");
                    decimal min = decimal.Parse(Console.ReadLine());
                    result = service.Query(o => o.TotalAmount >= min);
                    break;
            }

            if (result != null)
                foreach (var o in result)
                    Console.WriteLine(o);
        }
    }
}